<template>
  <span>
    <el-button type="primary" :disabled="disabled" :class="animation" circle  icon="iconfont icon-yuyin" @click="audio" plain :loading="connectState===1"></el-button>
  </span>
</template>

<script>
import WS2 from "@/library/js/ws2";
import { v4 as uuidv4 } from "uuid";
import RecordRTC from 'recordrtc'

export default {
  mixins: [WS2],
  name: "audio-button",
  components: {},
  props: {
    data: Object,
    disabled: Boolean
  },
  data: function () {
    return {
      clientId: null,
      connectState: 0,
      animation: null,
      recorder: null,
      errMsg:{
        0: "正常",
        1: "推流服务端链接流媒体服务网络故障",
        2: "推流服务端连接摄像头网络故障",
        3: "并行推流路数超限",
        4: "推流服务端主机内存不足",
        5: "onvif探测失败",
        6: "onvif 获取能力失败",
        7: "onvif 云台控制失败",
        11: "流媒体服务未启动", //前端页面判断
        12: "请求的 rtmp 流不存在；原因推流服务未运行或 rtmp 地址错误", //前端页面判断
      },
    };
  },
  mounted: function () {
    this.clientId = uuidv4();
  },
  methods: {
    async registVideoClient() {
        let data = {
          type_no: 200,
          regist_name:  this.clientId,
          project_id: this.data.camera_info.project_id,
        };
        this.sendData(data); //注册
    },
    async sendData(data){
        if(this.ws) this.ws.send(JSON.stringify(data));
    },
    audio(){
      if(this.connectState === 0){
        this.connectState = 1;
        this.createWS();
        this.ws.onopen = ()=>{
          this.registVideoClient();
          this.audioConnected();
        }
        this.ws.onmessage = ({ data }) => {
          data = JSON.parse(data);
          const code = data.error_no;
          if (code && code !== 5 && code !== 6 && code !== 7) {
            this.$message({
              type: "error",
              message: this.errMsg[data.error_no],
            });
          }
      		switch(data.type_no){
      			// 注册返回消息
      			case 300: 
      				if(data.regist_result)
      				{ 
                const cameraInfo = this.data.camera_info;
                let device = {
                    "type_no": 205,
                    "forward": true,
                    "project_id": this.data.project_id,
                    "from": this.clientId,   //前端ws id
                    "to": cameraInfo.push_id,
                    "camera_id": cameraInfo.uu_id,
                    "ip": cameraInfo.ip,
                    "user_name": cameraInfo.user_name,
                    "password": cameraInfo.password,
                    "camera_brand": 2,
                    "talk_ws_name": cameraInfo.uu_id + '@audio'
                }

                this.sendData(device);
      				}
      				else{
                this.closeAudio()
                this.$message({
                  type: 'warning',
                  message: data.message
                })
              }
      				break;
      			// 转发返回消息
      			case 301:
              if(!data.forward_result){         
                this.closeAudio()
                this.$message({
                  type: 'warning',
                  message: data.message
                })
              }
      				break
      			// 接收 推流服务器 返回的消息
      			case 101:
      				if(data.error_no === 0)	// 对讲邀请成功
      				{
                console.log("对讲邀请成功")
                this.initRecorder();
      				}
              else
              {
                this.closeAudio()
                this.$message({
                  type: 'warning',
                  message: '对讲邀请失败:' + data.message
                })
      				}
      				break;
      			default:break;
      		}
        }
      } else if(this.connectState == 2){
        this.closeAudio();
      }
    },
    closeAudio(){
      if(this.recorder) this.recorder.stopRecording();
      let data = {
        "type_no": 206,		//关闭
        "forward": true,
        "project_id": this.data.project_id,
        "from": this.clientId,   //前端ws id
        "to":  this.data.camera_info.push_id,
        "camera_id": this.data.camera_info.uu_id,
        "ip": this.data.camera_info.ip
      }
      this.sendData(data)
      this.ws.close();
      this.animation = null;
      this.connectState = 0;
    },
    audioConnected(){ 
      this.connectState = 2;
      this.animation = 'animation';
    },
    initRecorder(){
      this.captureMediaDevice(async  (media)=> {
        this.ws.binaryType = 'blob'
        this.recorder = new RecordRTC(media, {
            recorderType: RecordRTC.StereoAudioRecorder,// MediaStreamRecorder,
            type: 'audio',
            mimeType: 'audio/wav',
            timeSlice: 100, // pass this parameter
            // getNativeBlob: true,

            //audioBitsPerSecond: 128000,
            bufferSize: 1024,
            numberOfAudioChannels: 1,
            desiredSampRate: 16000,

            ondataavailable: async (blob) =>{
              if(this.ws) this.ws.send(blob)
            }
        });

        this.recorder.startRecording()

      })
    },
    captureMediaDevice(callback) {
        window.navigator.mediaDevices.getUserMedia({ audio: true }).then(function (media) {
            callback(media);
        }).catch(function (error) {
            this.$message({type: 'warning', message:'Unable to capture your camera. Please check console logs.'});
            console.error(error);
        });
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss"  scoped>
    .el-button{
      margin: 0;
      border: none;
      color: #29e449;
    }
    .el-button--primary.is-plain{
      background: gray;
      color: #29e449;
    }
 
    .el-button--primary.is-plain:hover{
      color: #fff;
    }

    .animation{
      animation: shanshuo 1.5s infinite;
      -webkit-animation:shanshuo 1.5s infinite;
      transform: scale(1.3);
      text-shadow: 0px 0px 4px #08f543;
    }
    @keyframes shanshuo{
      from{
        color:#500bf0;
        // text-shadow: 0px 0px 4px rgb(191, 223, 194);
      }
      to{
        // text-shadow: 0px 0px 10px   #0bf031;
        color:rgb(13, 236, 35);
      }
    }
</style>
